package cn.zongjie.day05;

public class Demo1 {
    public static void main(String[] args) {
        int[] arr1 = {8, 15, 26, 39, 60};
        int num = 39;
        int index = binarySearch(arr1, num);
        System.out.println(index < 0 ? "没有对应的索引" : num + "在数组中对应的索引为：" + index);
        //输出结果 39在数组中对应的索引为：3
    }

    public static int binarySearch(int[] arr, int num) {
        int min = 0;
        int max = arr.length - 1;
        while (min <= max) {
            int mid = (min + max) / 2;
            if (arr[mid] < num) {
                min = mid + 1;
            } else if (arr[mid] > num) {
                max = mid - 1;
            } else {
                return mid;
            }
        }
        return -1;
    }
}
